/*
 * This file is part of SSHTTPD.
 *
 * SSHTTPD is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SSHTTPD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/** @file 
 * Dynamicly loads object files as modules and provides an API for them to 
 * communicate with the main application.
 */

/* System includes. */
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>

/* App includes. */
#include "include/plugin.h" 
#include "include/utils.h"

/** Stores callback functions supplied by the modules. */
callback_t callbacks[16];

int callme(callback_t function) {
	callbacks[0] = function;
	(*callbacks[0])("test callback");
	return 0;
}

int cmod(const char *path) {
	void *module;
	mod_init init;
	modpack_t modpack;

	memset(&modpack, '\0', sizeof modpack);

	/* Load the module with a restricted local namespace and 
	 * grab its init function (mod_init's)adddress. */
	if((module = dlopen(path, RTLD_LAZY || RTLD_GLOBAL)) == NULL) {
		printf("%s\n", dlerror());
		return -1;
	}
	if((init = dlsym(module, "mod_init")) == NULL) {
		printf("%s\n", dlerror());
		return -1;
	}

	modpack.modref = module;
	modpack.event = event;
	modpack.callme = callme;

	/* Call the module init function and send it a modpack .*/
	init(&modpack);
	
	return 0;
}

int dcmod(modpack_t *modpack) {
	/* Call the module destructor if it exsists. */
	if(modpack->destruct != NULL)
		modpack->destruct();

	dlclose(modpack->modref);
	return 0;
}
